package com.hejielife.singlethreadedexecution5;

/**
 * 2019年8月2日 上午10:38:42
 * 
 * @author hejielife
 * @despribe 互斥锁
 */
public final class Mutex {
	private long locks = 0;
	private Thread owner = null;

	public synchronized void lock() {
		Thread me = Thread.currentThread();
		while (locks > 0 && owner != me) {
			try {
				wait();
			} catch (InterruptedException e) {
			}
		}
		owner = me;
		locks++;
	}

	public synchronized void unlock() {
		Thread me = Thread.currentThread();
		if (locks == 0 || owner != me) {
			return;
		}
		locks--;
		if (locks == 0) {
			owner = null;
			notifyAll();
		}
	}
}
